import Vue from 'vue'

export default {
	//返回上一页
	navigateBack() {
		if (getCurrentPages().length > 1) {
			uni.navigateBack()
		} else {
			uni.switchTab({
				url: '/'
			});
		}
	},
	//跳转
	navigator(url) {
		uni.navigateTo({
			url: url
		})
	},
	//获取导航栏高度
	getNavBarHeight() {
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		let barHeight = menuButtonInfo.height + (menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight']) * 2 +
			2
		// #endif
		// #ifdef APP-PLUS || H5
		let barHeight = 44
		// #endif
		return barHeight
	},
	//获取状态栏高度
	getStatusHeight() {
		return uni.getSystemInfoSync()['statusBarHeight']
	},
	//获取状态栏+导航栏高度
	getStatusBarHeight() {
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'] + menuButtonInfo.height + (menuButtonInfo.top -
			uni.getSystemInfoSync()['statusBarHeight']) * 2 + 2
		// #endif
		// #ifdef APP-PLUS || H5
		let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'] + 44
		// #endif
		return statusBarHeight
	},
	//获取状态栏+导航栏高度
	getStatusBarHeight() {
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'] + menuButtonInfo.height + (menuButtonInfo.top -
			uni.getSystemInfoSync()['statusBarHeight']) * 2 + 2
		// #endif
		// #ifdef APP-PLUS || H5
		let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'] + 44
		// #endif
		return statusBarHeight
	},
	//获取滚动高度
	getScrollHeight(reduce) {
		// #ifdef MP-WEIXIN || APP-PLUS
		return uni.getSystemInfoSync()['screenHeight'] - this.getStatusBarHeight() - uni.upx2px(reduce) - 10 + 'px'
		// #endif
		// #ifdef H5
		return 'calc( 100vh - 10px - ' + reduce + 'rpx)'
		uni.upx2px()
		// #endif
	},
	//px转rpx
	px2rpx(px) {
		return px / (uni.upx2px(px) / px)
	},
	//图片转base64
	imgBase64(url) {
		uni.request({
			url: url,
			method: 'GET',
			responseType: 'arraybuffer',
			success: async res => {
				return 'data:image/jpeg;base64,' + wx.arrayBufferToBase64(res.data)
			}
		});
	},
	//获取时间
	parseTime(time, cFormat) {
		if (arguments.length === 0) {
			return null
		}
		const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
		let date
		if (typeof time === 'object') {
			date = time
		} else {
			if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
				time = parseInt(time)
			}
			if (typeof time === 'number' && time.toString().length === 10) {
				time = time * 1000
			}
			date = new Date(time)
		}
		const formatObj = {
			y: date.getFullYear(),
			m: date.getMonth() + 1,
			d: date.getDate(),
			h: date.getHours(),
			i: date.getMinutes(),
			s: date.getSeconds(),
			a: date.getDay()
		}
		const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
			const value = formatObj[key]
			// Note: getDay() returns 0 on Sunday
			if (key === 'a') {
				return ['日', '一', '二', '三', '四', '五', '六'][value]
			}
			return value.toString().padStart(2, '0')
		})
		return time_str
	},
	//获取路径距离
	distance(lat1, lng1, lat2, lng2) {
		if (lat1 && lng1 && lat2 && lng2) {
			let radLat1 = this.rad(lat1);
			let radLat2 = this.rad(lat2);
			let a = radLat1 - radLat2;
			let b = this.rad(lng1) - this.rad(lng2);
			let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
				.pow(Math.sin(b / 2), 2)));
			s = s * 6378.137;
			// EARTH_RADIUS;
			s = Math.round(s * 10000) / 10000;
			return s
		} else {
			return 0
		}
	},
	rad(d) {
		return d * Math.PI / 180.0
	},
	//获取几天后日期
	getDateByDay(number) {
		var date1 = new Date();
		var date2 = new Date(date1);
		date2.setDate(date1.getDate() + number);
		return date2.getFullYear() + "-" + (date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2
		.getMonth() + 1) + "-" + (date2.getDate() < 10 ? '0' + date2.getDate() : date2.getDate())
	},
	//满一万转w
	tenThousandChange(number) {
		if (Number(number) < 10000) {
			return number
		} else {
			return (Number(number) / 10000).toFixed(1)
		}
	},
	// 回显数据字典
	selectLabel(datas, value) {
		var actions = [];
		Object.keys(datas).some((key) => {
			if (datas[key].value == ('' + value)) {
				actions.push(datas[key].label);
				return true;
			}
		})
		return actions.join('');
	},
	// 回显数据字典
	selectDictLabel(datas, value) {
		var actions = [];
		Object.keys(datas).some((key) => {
			if (datas[key].dictValue == ('' + value)) {
				actions.push(datas[key].dictLabel);
				return true;
			}
		})
		return actions.join('');
	},
	// 拨打电话
	makePhoneCall(phoneNumber) {
		uni.makePhoneCall({
			phoneNumber: phoneNumber //仅为示例
		});
	},
	// 预览图片
	previewImage(imgarr, current) {
		uni.previewImage({
			urls: imgarr,
			current: current,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function(data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	},
	/*
	 * 单图上传
	 * @param object opt
	 * @param callable successCallback 成功执行方法 data 
	 * @param callable errorCallback 失败执行方法 
	 */
	uploadImageOne: function(opt, successCallback, errorCallback) {
		let that = this;
		if (typeof opt === 'string') {
			let url = opt;
			opt = {};
			opt.url = url;
		}
		let count = opt.count || 1,
			sizeType = opt.sizeType || ['compressed'],
			sourceType = opt.sourceType || ['album', 'camera'],
			is_load = opt.is_load || true,
			uploadUrl = opt.url || '',
			inputName = opt.name || 'file',
			fileType = opt.fileType || 'image';
		uni.chooseImage({
			count: count, //最多可以选择的图片总数  
			sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有  
			sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
			success: function(res) {
				//启动上传等待中...  
				uni.showLoading({
					title: '图片上传中'
				});
				console.log(res.tempFilePaths[0], ' --------------》')
				uni.uploadFile({
					url: Vue.prototype.baseUrl + '/' + uploadUrl,
					filePath: res.tempFilePaths[0],
					fileType: fileType,
					name: inputName,
					formData: {
						'filename': inputName
					},
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
						//[TOKENNAME]: 'Bearer ' + store.state.app.token
					},
					success: function(res) {
						uni.hideLoading();
						if (res.statusCode == 403) {
							uni.showToast({
								title: res.data,
								icon: 'none'
							})
						} else {
							let data = res.data ? JSON.parse(res.data) : {};
							if (data.code == 200) {
								successCallback && successCallback(data)
							} else {
								errorCallback && errorCallback(data);

								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
							}
						}
					},
					fail: function(res) {
						uni.hideLoading();
						uni.showToast({
							title: '上传图片失败',
							icon: 'none'
						})
					}
				})
			}
		})
	},
	/*
	 * 单图上传压缩版
	 * @param object opt
	 * @param callable successCallback 成功执行方法 data 
	 * @param callable errorCallback 失败执行方法 
	 */
	uploadImageChange: function(opt, successCallback, errorCallback, sizeCallback) {
		let that = this;
		if (typeof opt === 'string') {
			let url = opt;
			opt = {};
			opt.url = url;
		}
		let count = opt.count || 1,
			sizeType = opt.sizeType || ['compressed'],
			sourceType = opt.sourceType || ['album', 'camera'],
			is_load = opt.is_load || true,
			uploadUrl = opt.url || '',
			inputName = opt.name || 'file',
			fileType = opt.fileType || 'image';
		uni.chooseImage({
			count: count, //最多可以选择的图片总数  
			sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有  
			sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
			success: function(res) {
				//启动上传等待中...  
				let imgSrc
				uni.getImageInfo({
					src: res.tempFilePaths[0],
					success(ress) {
						uni.showLoading({
							title: '图片上传中',
						});
						if (res.tempFiles[0].size <= 2097152) {
							uploadImg(ress.path)
							return
						}
						let canvasWidth, canvasHeight, xs, maxWidth = 750
						xs = ress.width / ress.height // 宽高比例
						if (ress.width > maxWidth) {
							canvasWidth = maxWidth // 这里是最大限制宽度
							canvasHeight = maxWidth / xs
						} else {
							canvasWidth = ress.width
							canvasHeight = ress.height
						}
						sizeCallback && sizeCallback({
							w: canvasWidth,
							h: canvasHeight
						})
						let canvas = uni.createCanvasContext('canvas');
						canvas.width = canvasWidth
						canvas.height = canvasHeight
						canvas.clearRect(0, 0, canvasWidth, canvasHeight);
						canvas.drawImage(ress.path, 0, 0, canvasWidth, canvasHeight)
						canvas.save();
						// 这里的画布drawImage是一种异步属性  可能存在未绘制全就执行了draw的问题  so添加延迟
						setTimeout(e => {
							canvas.draw(true, () => {
								uni.canvasToTempFilePath({
									canvasId: 'canvas',
									fileType: 'JPEG',
									destWidth: canvasWidth,
									destHeight: canvasHeight,
									quality: 0.7,
									success: function(canvasPath) {
										uploadImg(canvasPath
											.tempFilePath)
									}
								})
							});
						}, 200)


					}
				})
			}
		})

		function uploadImg(filePath) {
			uni.uploadFile({
				url: Vue.prototype.baseUrl + '/' + uploadUrl,
				filePath,
				fileType: fileType,
				name: inputName,
				formData: {
					'file': inputName
				},
				header: {
					// #ifdef MP
					"Content-Type": "multipart/form-data",
					// #endif
					//[TOKENNAME]: 'Bearer ' + store.state.app.token
				},
				success: function(res) {
					uni.hideLoading();
					if (res.statusCode == 403) {
						uni.showToast({
							title: res.data,
							icon: 'none'
						})
					} else {
						let data = res.data ? JSON.parse(res.data) : {};
						if (data.code == 200) {
							successCallback && successCallback(data)
						} else {
							errorCallback && errorCallback(data);

							uni.showToast({
								title: data.msg,
								icon: 'none'
							})
						}
					}
				},
				fail: function(res) {
					uni.hideLoading();
					uni.showToast({
						title: '上传图片失败',
						icon: 'none'
					})
				}
			})
		}
	},
	
	/**
	 * 获取url 中参数
	 * @param url url地址
	 * @param key 参数key
	 */
	getUrlParamValue(key,url=window.location.search) {
		// 获取搜索参数
		let searchParams = new URLSearchParams(url);
		let paramValue = searchParams.get(key);
		// 如果在搜索参数中找不到，再从哈希参数中找
		if (!paramValue) {
			let hashIndex = window.location.hash.indexOf('?');
			if (hashIndex !== -1) {
				let hashParams = new URLSearchParams(window.location.hash.substring(hashIndex + 1));
				paramValue = hashParams.get(key);
			}
		}
		return paramValue;
	}
	
	
}